/* 用户管理模块 */

const router = require("koa-router")();
const User = require("../models/userSchema");
const Menu = require("../models/menuSchema");
const Role = require("../models/roleSchema");
const Counter = require("../models/counterSchema");
const util = require("../utils/util");
const jwt = require("jsonwebtoken");
const md5 = require("md5");

router.prefix("/users");

//登录
router.post("/login", async (ctx) => {
    try {
        const { userName, userPwd } = ctx.request.body;

        /*
         * findOne方法第二个参数是指定返回字段
         * 1：'userId userName userEmail state role deptId roleList' //字符串返回，空格分隔
         * 2：{userId:1,userName:0} //对象方式返回，1是返回，0不返回
         * findOne方法后接select方法查找某个字段并返回
         * 1：findOne().select('userId')
         * */
        const res = await User.findOne(
            {
                userName,
                userPwd,
            },
            //返回指定字段
            "userId userName userEmail state role deptId roleList"
        );
        if (res) {
            const data = res._doc;
            //第一个参数为内容，第二个是密钥，第三个是token过期时间
            //生成token
            const token = jwt.sign(
                {
                    data: data,
                },
                "admin",
                //数字单位是秒，字符串里是数字单位是毫秒，字符串里数字带单位的按单位算（'1h'：一小时，'1d'：一天）
                {
                    expiresIn: "1h",
                }
            );
            data.token = token;
            ctx.body = util.success(data);
        } else {
            ctx.body = util.fail("账号或密码不正确", util.CODE.USER_ACCOUNT_ERROR);
        }
    } catch (error) {
        ctx.body = util.fail(error);
    }
});

//用户列表
router.get("/list", async (ctx) => {
    const { userId, userName, state } = ctx.request.query;
    const { page, skipIndex } = util.pager(ctx.request.query);
    let params = {};
    if (userId) params.userId = userId;
    if (userName) params.userName = userName;
    if (state && state !== "0") params.state = parseInt(state);
    try {
        // 根据条件查询所有用户列表
        const query = User.find(params, {
            _id: 0,
            userPwd: 0,
        });
        const list = await query.skip(skipIndex).limit(page.pageSize);
        const total = await User.countDocuments(params);

        ctx.body = util.success({
            page: {
                ...page,
                total,
            },
            list,
        });
    } catch (error) {
        ctx.body = util.fail(`查询异常:${error.stack}`);
    }
});

//获取所有用户列表（不分页）
router.get("/all/list", async (ctx) => {
    try {
        const list = await User.find({}, "userId userName userEmail");
        ctx.body = util.success(list);
    } catch (err) {
        ctx.body = util.fail(err.stack);
    }
});

//用户删除/批量删除
router.post("/delete", async (ctx) => {
    //待删除的用户id数组
    const { userIds } = ctx.request.body;
    // const res = await User.updateMany(
    //     {
    //         userId: {
    //             $in: userIds,
    //         },
    //     },
    //     {
    //         $set: {
    //             state: 2,
    //         },
    //     }
    // );
    // if (res.modifiedCount) {
    //     ctx.body = util.success(res, `共删除成功${res.modifiedCount}条`);
    //     return;
    // }
    const res = await User.deleteMany({ userId: { $in: userIds } });
    console.log(res);
    if (res.deletedCount) {
        ctx.body = util.success(res, `共删除成功${res.deletedCount}条`);
        return;
    }
    ctx.body = util.fail("删除失败");
});

//用户新增/编辑
router.post("/operate", async (ctx) => {
    const { userId, userName, userEmail, mobile, job, state, roleList, deptId, action } = ctx.request.body;
    if (action === "add") {
        if (!userName || !userEmail || !deptId) {
            ctx.body = util.fail("参数错误", util.CODE.PARAM_ERROR);
            return;
        }
        const res = await User.findOne(
            {
                $or: [
                    {
                        userName,
                    },
                    {
                        userEmail,
                    },
                ],
            },
            "_id userName userEmail"
        );
        if (res) {
            ctx.body = util.fail("用户已存在");
        } else {
            const doc = await Counter.findOneAndUpdate(
                {
                    _id: "userId",
                },
                {
                    $inc: {
                        sequence_value: 1,
                    },
                },
                {
                    new: true,
                }
            );
            try {
                const user = new User({
                    userId: doc.sequence_value,
                    // userPwd: md5("123456"),
                    userPwd: "123456", //先不加密密码
                    userName,
                    userEmail,
                    mobile,
                    role: 1,
                    job,
                    state,
                    roleList,
                    deptId,
                });
                user.save();
                ctx.body = util.success({}, "用户创建成功");
            } catch (error) {
                ctx.body = util.fail(error.stack, "用户创建失败");
            }
        }
    } else {
        if (!deptId) {
            ctx.body = util.fail("部门不能为空", util.CODE.PARAM_ERROR);
            return;
        }
        try {
            const res = await User.findOneAndUpdate(
                {
                    userId,
                },
                {
                    mobile,
                    job,
                    state,
                    roleList,
                    deptId,
                }
            );
            ctx.body = util.success({}, "更新成功");
        } catch (error) {
            ctx.body = util.fail(error.stack, "更新失败");
        }
    }
});

//获取用户对应的权限菜单
router.get("/getPermissionList", async (ctx) => {
    // 获取token
    let authorization = ctx.request.headers.authorization;
    // 解密token 得到里面的数据
    let { data } = util.decoded(authorization);
    let menuList = await getMenuList(data.role, data.roleList);
    let actionList = getActionList(JSON.parse(JSON.stringify(menuList)));
    ctx.body = util.success({ menuList, actionList });
});

//获取菜单列表
const getMenuList = async (userRole, roleKeys) => {
    let rootList = [];
    // 系统管理员
    if (userRole == 0) {
        rootList = (await Menu.find({})) || [];
    } else {
        // 普通用户
        // 根据用户拥有的角色，获取权限列表
        // 查找用户对应的角色有哪些
        let roleList = await Role.find({ _id: { $in: roleKeys } });
        let permissionList = [];
        // 去除重复的权限，比如开发和产品都可查看同一个功能模块
        roleList.map((role) => {
            let { checkedKeys, halfCheckedKeys } = role.permissionList;
            permissionList = permissionList.concat([...checkedKeys, ...halfCheckedKeys]);
        });
        permissionList = Array.from(new Set(permissionList));
        rootList = await Menu.find({ _id: { $in: permissionList } });
    }
    return util.getTreeMenu(rootList, null, []);
};

//获取用户对应的操作权限列表
const getActionList = (list) => {
    const actionList = [];
    const deep = (arr) => {
        while (arr.length) {
            let item = arr.pop();
            if (item.action) {
                item.action.map((action) => {
                    actionList.push(action.menuCode);
                });
            }
            if (item.children && !item.action) {
                deep(item.children);
            }
        }
    };
    deep(list);
    return actionList;
};
module.exports = router;
